<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'my_reservations':
                // 获取我的预约列表
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $reservations = $db->fetchAll("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time,
                           (SELECT COUNT(*) FROM reservation_companions WHERE reservation_id = r.id) as companion_count
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    WHERE r.user_id = ?
                    ORDER BY r.visit_date DESC, r.created_at DESC
                ", [$user['id']]);
                
                Response::success($reservations, '获取成功');
                break;
                
            case 'reservation_detail':
                // 获取预约详情
                $reservationId = (int)($_GET['id'] ?? 0);
                if (!$reservationId) {
                    Response::error('缺少预约ID');
                }
                
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $reservation = $db->fetchOne("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time, u.nickname
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    WHERE r.id = ? AND r.user_id = ?
                ", [$reservationId, $user['id']]);
                
                if (!$reservation) {
                    Response::error('预约不存在');
                }
                
                // 获取同伴信息
                $companions = $db->fetchAll("
                    SELECT * FROM reservation_companions WHERE reservation_id = ?
                ", [$reservationId]);
                
                $reservation['companions'] = $companions;
                
                Response::success($reservation, '获取成功');
                break;
                
            case 'available_dates':
                // 获取所有日期（包含可预约状态） - DEBUG版本
                $startDate = $_GET['start_date'] ?? date('Y-m-d');
                $endDate = $_GET['end_date'] ?? date('Y-m-d', strtotime('+7 days'));
                
                $allDates = [];
                $current = strtotime($startDate);
                $end = strtotime($endDate);
                
                // 确保绝对包含所有日期
                $dateCount = 0;
                while ($current <= $end && $dateCount < 365) { // 防止无限循环
                    $dateStr = date('Y-m-d', $current);
                    $dayOfWeek = (int)date('N', $current);
                    
                    // 基础日期信息 - 100%包含
                    $dateItem = [
                        'date' => $dateStr,
                        'day_of_week' => $dayOfWeek,
                        'day_name' => date('l', $current),
                        'day_name_zh' => ['', '一', '二', '三', '四', '五', '六', '日'][$dayOfWeek] ?? $dayOfWeek,
                        'available' => false,
                        'reason' => '检查中...',
                        'schedule' => null,
                        'available_slots' => 0,
                        'total_slots' => 0,
                        'debug_info' => [
                            'timestamp' => $current,
                            'iteration' => $dateCount
                        ]
                    ];
                    
                    // 安全地尝试获取详细信息
                    if (function_exists('checkDateAvailability')) {
                        try {
                            $availability = checkDateAvailability($dateStr);
                            if (is_array($availability)) {
                                $dateItem['available'] = !empty($availability['available']);
                                $dateItem['reason'] = $availability['reason'] ?? ($dateItem['available'] ? null : '未知原因');
                                $dateItem['schedule'] = $availability['schedule'] ?? null;
                                $dateItem['available_slots'] = (int)($availability['available_slots'] ?? 0);
                                $dateItem['total_slots'] = (int)($availability['total_slots'] ?? 0);
                            } else {
                                $dateItem['reason'] = 'checkDateAvailability返回非数组';
                            }
                        } catch (Exception $e) {
                            $dateItem['reason'] = 'API异常: ' . $e->getMessage();
                        } catch (Error $e) {
                            $dateItem['reason'] = 'PHP错误: ' . $e->getMessage();
                        }
                    } else {
                        $dateItem['reason'] = 'checkDateAvailability函数不存在';
                    }
                    
                    $allDates[] = $dateItem;
                    $current = strtotime('+1 day', $current);
                    $dateCount++;
                }
                
                Response::success([
                    'dates' => $allDates,
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                    'total_count' => count($allDates),
                    'debug' => [
                        'iterations' => $dateCount,
                        'current_time' => date('Y-m-d H:i:s')
                    ]
                ], '获取成功');
                break;
                
            case 'available_slots':
                // 获取某日期可用时段
                $visitDate = $_GET['date'] ?? '';
                if (!$visitDate) {
                    Response::error('缺少日期参数');
                }
                
                $slots = $db->fetchAll("SELECT * FROM museum_time_slots WHERE is_active = 1 ORDER BY sort_order");
                $availableSlots = [];
                
                foreach ($slots as $slot) {
                    $availability = checkDateAvailability($visitDate, $slot['id']);
                    if ($availability['available']) {
                        $slot['available_count'] = $availability['available_slots'];
                        $availableSlots[] = $slot;
                    }
                }
                
                Response::success($availableSlots, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $user = $auth->getCurrentUser();
        if (!$user) {
            Response::authError('请先登录');
        }
        
        switch ($action) {
            case 'create':
                // 创建预约
                if (!isset($input['visit_date']) || !isset($input['time_slot_id']) || !isset($input['visitor_count'])) {
                    Response::error('缺少必要参数');
                }
                
                $visitDate = $input['visit_date'];
                $timeSlotId = (int)$input['time_slot_id'];
                $visitorCount = (int)$input['visitor_count'];
                $visitorName = $input['visitor_name'] ?? $user['nickname'] ?? '';
                $visitorPhone = $input['visitor_phone'] ?? $user['phone'] ?? '';
                $visitorIdCard = $input['visitor_id_card'] ?? '';
                $notes = $input['notes'] ?? '';
                $companions = $input['companions'] ?? [];
                
                // 验证输入
                if ($visitorCount < 1 || $visitorCount > 10) {
                    Response::error('参观人数必须在1-10之间');
                }
                
                if (empty($visitorName) || empty($visitorPhone)) {
                    Response::error('参观者姓名和电话不能为空');
                }
                
                // 检查日期和时段可用性
                $availability = checkDateAvailability($visitDate, $timeSlotId);
                if (!$availability['available']) {
                    Response::error($availability['reason']);
                }
                
                if ($availability['available_slots'] < $visitorCount) {
                    Response::error('剩余名额不足，当前可预约：' . $availability['available_slots'] . '人');
                }
                
                // 检查用户是否已有该日期的预约
                $existingReservation = $db->fetchOne("
                    SELECT id FROM reservations 
                    WHERE user_id = ? AND visit_date = ? AND status IN ('pending', 'confirmed')
                ", [$user['id'], $visitDate]);
                
                if ($existingReservation) {
                    Response::error('您已预约该日期，请勿重复预约');
                }
                
                // 生成预约码
                $reservationCode = generateReservationCode();
                
                try {
                    // 开始事务
                    $db->getConnection()->beginTransaction();
                    
                    // 创建预约
                    $reservationId = $db->insert('reservations', [
                        'user_id' => $user['id'],
                        'reservation_type' => 'personal',
                        'visit_date' => $visitDate,
                        'time_slot_id' => $timeSlotId,
                        'visitor_count' => $visitorCount,
                        'visitor_name' => $visitorName,
                        'visitor_phone' => $visitorPhone,
                        'visitor_id_card' => $visitorIdCard,
                        'reservation_code' => $reservationCode,
                        'status' => 'confirmed',
                        'notes' => $notes
                    ]);
                    
                    if (!$reservationId) {
                        throw new Exception('创建预约失败');
                    }
                    
                    // 添加同伴信息
                    foreach ($companions as $companion) {
                        if (empty($companion['name'])) continue;
                        
                        $db->insert('reservation_companions', [
                            'reservation_id' => $reservationId,
                            'name' => $companion['name'],
                            'id_card' => $companion['id_card'] ?? '',
                            'phone' => $companion['phone'] ?? '',
                            'relationship' => $companion['relationship'] ?? ''
                        ]);
                    }
                    
                    // 更新统计
                    updateReservationStatistics($visitDate, $timeSlotId);
                    
                    // 提交事务
                    $db->getConnection()->commit();
                    
                    Response::success([
                        'reservation_id' => $reservationId,
                        'reservation_code' => $reservationCode,
                        'visit_date' => $visitDate,
                        'visitor_count' => $visitorCount
                    ], '预约成功');
                    
                } catch (Exception $e) {
                    $db->getConnection()->rollBack();
                    Response::error('预约失败：' . $e->getMessage());
                }
                break;
                
            case 'cancel':
                // 取消预约
                if (!isset($input['reservation_id'])) {
                    Response::error('缺少预约ID');
                }
                
                $reservationId = (int)$input['reservation_id'];
                
                $reservation = $db->fetchOne("
                    SELECT * FROM reservations 
                    WHERE id = ? AND user_id = ? AND status IN ('pending', 'confirmed')
                ", [$reservationId, $user['id']]);
                
                if (!$reservation) {
                    Response::error('预约不存在或无法取消');
                }
                
                // 检查是否可以取消（例如：参观前2小时不能取消）
                $visitDateTime = $reservation['visit_date'] . ' ' . ($reservation['start_time'] ?? '09:00:00');
                $cancelDeadline = strtotime('-2 hours', strtotime($visitDateTime));
                
                if (time() > $cancelDeadline) {
                    Response::error('参观前2小时内无法取消预约');
                }
                
                $result = $db->update('reservations', [
                    'status' => 'cancelled',
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $reservationId]);
                
                if ($result) {
                    // 更新统计
                    updateReservationStatistics($reservation['visit_date'], $reservation['time_slot_id']);
                    Response::success(['reservation_id' => $reservationId], '取消成功');
                } else {
                    Response::error('取消失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 生成预约码
function generateReservationCode() {
    return strtoupper(substr(md5(uniqid() . time()), 0, 12));
}

// 更新预约统计
function updateReservationStatistics($visitDate, $timeSlotId) {
    global $db;
    
    $stats = $db->fetchOne("
        SELECT 
            COUNT(CASE WHEN status IN ('pending', 'confirmed') THEN 1 END) as reserved_count,
            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
            COUNT(CASE WHEN check_in_time IS NOT NULL THEN 1 END) as checked_in_count
        FROM reservations 
        WHERE visit_date = ? AND time_slot_id = ?
    ", [$visitDate, $timeSlotId]);
    
    $db->query("
        INSERT INTO reservation_statistics (visit_date, time_slot_id, reserved_count, cancelled_count, checked_in_count)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        reserved_count = VALUES(reserved_count),
        cancelled_count = VALUES(cancelled_count),
        checked_in_count = VALUES(checked_in_count),
        updated_at = CURRENT_TIMESTAMP
    ", [
        $visitDate, 
        $timeSlotId, 
        $stats['reserved_count'], 
        $stats['cancelled_count'], 
        $stats['checked_in_count']
    ]);
}

// 检查日期可用性函数（重构版本，总是返回完整信息）
function checkDateAvailability($visitDate, $timeSlotId = null) {
    global $db;
    
    $result = [
        'available' => false,
        'reason' => null,
        'schedule' => null,
        'available_slots' => 0,
        'total_slots' => 0
    ];
    
    // 检查日期格式
    $dateObj = DateTime::createFromFormat('Y-m-d', $visitDate);
    if (!$dateObj) {
        $result['reason'] = '日期格式无效';
        return $result;
    }
    
    $today = date('Y-m-d');
    if ($visitDate < $today) {
        $result['reason'] = '不能预约过去的日期';
        return $result;
    }
    
    // 检查预约提前天数限制
    $advanceDaysConfig = $db->fetchOne("SELECT config_value FROM museum_config WHERE config_key = 'advance_booking_days'");
    $advanceDays = (int)($advanceDaysConfig['config_value'] ?? 30); // 默认30天
    $maxDate = date('Y-m-d', strtotime("+{$advanceDays} days"));
    if ($visitDate > $maxDate) {
        $result['reason'] = "只能预约{$advanceDays}天内的日期";
        return $result;
    }
    
    // 检查是否为休息日
    $dayOfWeek = date('N', strtotime($visitDate)); // 1=周一, 7=周日
    $schedule = $db->fetchOne("SELECT * FROM museum_schedule WHERE day_of_week = ?", [$dayOfWeek]);
    $result['schedule'] = $schedule;
    
    if (!$schedule || !$schedule['is_open']) {
        $result['reason'] = '该日期为休息日';
        return $result;
    }
    
    // 检查特殊闭馆日期（单次和年度重复）
    $closure = $db->fetchOne("
        SELECT * FROM museum_closure_dates 
        WHERE is_active = 1 
        AND (
            (closure_type = 'once' AND closure_date = ?) 
            OR (closure_type = 'yearly' AND DATE_FORMAT(?, '%m-%d') = DATE_FORMAT(closure_date, '%m-%d'))
        )
    ", [$visitDate, $visitDate]);
    
    if ($closure) {
        $result['reason'] = '该日期为闭馆日：' . ($closure['reason'] ?? '');
        return $result;
    }
    
    // 检查日期范围闭馆规则
    $rangeClosure = $db->fetchOne("
        SELECT * FROM museum_closure_dates 
        WHERE is_active = 1 
        AND closure_type = 'range'
        AND ? BETWEEN closure_date AND closure_end_date
    ", [$visitDate]);
    
    if ($rangeClosure) {
        $result['reason'] = '该日期为闭馆日：' . ($rangeClosure['reason'] ?? '');
        return $result;
    }
    
    // 如果指定了时段ID，只检查该时段
    if ($timeSlotId) {
        $slot = $db->fetchOne("SELECT * FROM museum_time_slots WHERE id = ? AND is_active = 1", [$timeSlotId]);
        if (!$slot) {
            $result['reason'] = '时段不存在或未启用';
            return $result;
        }
        
        $reserved = $db->fetchOne("
            SELECT COALESCE(SUM(visitor_count), 0) as total 
            FROM reservations 
            WHERE visit_date = ? AND time_slot_id = ? AND status IN ('pending', 'confirmed')
        ", [$visitDate, $timeSlotId]);
        
        $availableSlots = $slot['max_visitors'] - ($reserved['total'] ?? 0);
        
        return [
            'available' => $availableSlots > 0,
            'available_slots' => $availableSlots,
            'max_visitors' => $slot['max_visitors'],
            'slot_info' => $slot,
            'schedule' => $schedule,
            'reason' => $availableSlots > 0 ? null : '该时段已满'
        ];
    }
    
    // 计算当天所有时段的总可用数量
    $slots = $db->fetchAll("SELECT * FROM museum_time_slots WHERE is_active = 1");
    $totalAvailable = 0;
    $totalMax = 0;
    
    foreach ($slots as $slot) {
        $reserved = $db->fetchOne("
            SELECT COALESCE(SUM(visitor_count), 0) as total 
            FROM reservations 
            WHERE visit_date = ? AND time_slot_id = ? AND status IN ('pending', 'confirmed')
        ", [$visitDate, $slot['id']]);
        
        $slotAvailable = $slot['max_visitors'] - ($reserved['total'] ?? 0);
        $totalAvailable += max(0, $slotAvailable);
        $totalMax += $slot['max_visitors'];
    }
    
    $result['available'] = $totalAvailable > 0;
    $result['available_slots'] = $totalAvailable;
    $result['total_slots'] = $totalMax;
    
    if (!$result['available'] && $totalMax > 0) {
        $result['reason'] = '当日所有时段已满';
    }
    
    return $result;
}
?>